<?php
declare (strict_types = 1);

namespace app\api\controller;

use app\api\model\Auth;
use app\api\model\Role;
use app\api\service\Token;
use think\exception\ValidateException;
use think\Request;

class Login
{
    /**
     * @return string
     */
   public function doLogin(){
       try {
//           $username = \request()->post('username');
//           $password = \request()->post('password');
//           $code = \request()->post('code');
//           validate(\app\api\validate\Login::class)->check(['username' => $username,'password' => $password,'code' => $code]);

           # 注意 验证器字段需要和传送过来的参数名称一致
           $param = \request()->all();
           validate(\app\api\validate\Login::class)->check($param);

           #  验证验证码
           // 检测输入的验证码是否正确，$value为用户输入的验证码字符串
//           if( !captcha_check($param['code']))
//           {
//               // 验证失败
//               return  fail([],"验证码错误",2001);
//           }
           # 验证用户名、密码
           $adminInfo = \app\api\model\Admin::where('username',$param['username'])->find();
           if (empty($adminInfo)) {
               return  fail([],"用户名不存在");
           }

           if ($adminInfo->password != md5($param['password'])) {
               return  fail([],"密码错误");
           }

           # 查询用户对应的权限
           if ($adminInfo->role_id !=1) {
               # 根据角色di查询权限id
               $auth_ids =Role::find($adminInfo->role_id)->auth_ids;
               # 根据权限id查询权限
               $auth = Auth::whereIn('id',$auth_ids)->select()->toArray();
           } else {
               # 超级管理员查询所有的权限
               $auth = Auth::select()->toArray();
           }

           // 返回给客户端
           $auth = parent_child($auth);

           # 登录成功  颁布凭证
           $data = [
               'token' => (new Token())->encode($adminInfo->id),
               'auth' => $auth,// 返回给客户端进行展示
           ];
            return success($data);

       }catch (ValidateException $validateException) {
           return fail([],$validateException->getError(),2001);
       }
   }

    /**
     * 获取验证码的接口
     */
   public function getCaptcha(){
       $data = [
           'src' => 'http://www.month.com/'.captcha_src(),
           'uniqid' => uniqid((string)mt_rand(100000, 999999)),
       ];

       return success($data);
   }
}
